use axum::{
	async_trait,
	extract::{Extension, FromRequest, TypedHeader},
};
use http::request::Parts;
use headers::{authorization::Bearer, Authorization};
use CookieShopRust::{
	domain::error::{ApiError, Error},
	domain::user_bean::UserBean,
};
use crate::{
	utils::jwt_util,
};

use crate::serviceimpl::user_service::find_user_by_id;

#[async_trait]
impl<S, B> FromRequest<S, B> for UserBean
where
B: Send + 'static,
S: Send + Sync,
{
	type Rejection = ApiError;

	async fn from_request(req: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
		let TypedHeader(Authorization(bearer)) =
			TypedHeader::<Authorization<Bearer>>::from_request(req)
				.await
				.map_err(|err| Error::from(err))?;
		let claims = jwt_util::verify(bearer.token())?;
		Ok(find_user_by_id(claims.sub).await?)
	}
}
